package com._520it.crm.service.impl;

import com._520it.crm.domain.Employee;
import com._520it.crm.domain.SystemMenu;
import com._520it.crm.mapper.SystemMenuMapper;
import com._520it.crm.page.PageResult;
import com._520it.crm.query.QueryObject;
import com._520it.crm.service.ISystemMenuService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
@Service
public class SystemMenuServiceImpl implements ISystemMenuService {
	@Autowired
	private SystemMenuMapper systemMenuMapper;
	
	public int deleteByPrimaryKey(Long id) {
		return systemMenuMapper.deleteByPrimaryKey(id);
	}

	public int insert(SystemMenu record) {
		return systemMenuMapper.insert(record);
	}

	public SystemMenu selectByPrimaryKey(Long id) {
		return systemMenuMapper.selectByPrimaryKey(id);
	}

	public List<SystemMenu> selectAll() {
		return systemMenuMapper.selectAll();
	}

	public int updateByPrimaryKey(SystemMenu record) {
		return systemMenuMapper.updateByPrimaryKey(record);
	}

	@Override
	public PageResult queryPage(QueryObject qo) {
		Long count = systemMenuMapper.queryPageCount(qo);
		if(count<=0){
			return new PageResult(0L, Collections.EMPTY_LIST);
		}
		List<SystemMenu> result = systemMenuMapper.queryPageDataResult(qo);
		PageResult pageResult = new PageResult(count,result);
		return pageResult;
	}

	@Override
	public List<SystemMenu> queryTree() {
		return systemMenuMapper.queryTree();
	}

	@Override
	public List<SystemMenu> queryForRole() {
		return systemMenuMapper.queryTree();
	}

	@Override
	public List<Long> queryMenuIdsListForRole(Long roleId) {
		return systemMenuMapper.systemMenuMapper(roleId);
	}

	@Override
	public List<SystemMenu> indexMenu() {
		Employee current = (Employee) SecurityUtils.getSubject().getPrincipal();
		List<SystemMenu> menuList = systemMenuMapper.queryTree();
		//如果是管理员 显示所有菜单
		if(current.isAdmin()){
			return menuList;
		}else{
			//如果不是, 根据id查询出该用户拥有的菜单权限 id集合
			List<Long> menuIds = systemMenuMapper.queryMenuIdListByEmployeeId(current.getId());
			//删除掉该用户没有的菜单权限
			filterMenu(menuList,menuIds);
			return menuList;
		}
	}

	private void filterMenu(List<SystemMenu> menuList, List<Long> menuIds) {
		SystemMenu menu = null;
		//删除要倒着删
		for (int i = menuList.size() -1 ;i >=0 ;i--) {
			menu = menuList.get(i);
			Long id = menu.getId();
			if(!menuIds.contains(id)){
				menuList.remove(i);
			}
			if(menu.getChildren() != null && menu.getChildren().size()>0 ){
				filterMenu(menu.getChildren(),menuIds);
			}
		}
	}
}
